/*
 * Famon (http://code.google.com/p/famon/)
 * Copyright (c) 2010 Carl Crous.
 *
 * This file is part of Famon.
 *
 * Famon is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Famon is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Famon.  If not, see <http://www.gnu.org/licenses/>.
 */

package za.org.foobar.famon.frontend.client.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.HTML;
import org.gwtportlets.portlet.client.WidgetFactory;
import org.gwtportlets.portlet.client.layout.RowLayout;
import org.gwtportlets.portlet.client.ui.Dialog;
import org.gwtportlets.portlet.client.ui.LayoutPanel;
import org.gwtportlets.portlet.client.ui.Portlet;
import org.gwtportlets.portlet.smartgwt.client.DataTransferObject;
import org.gwtportlets.portlet.smartgwt.client.SmartPortlet;
import org.gwtportlets.portlet.smartgwt.client.SmartPortletFactory;
import za.org.foobar.famon.frontend.client.Famon;
import za.org.foobar.famon.frontend.client.FamonPage;
import za.org.foobar.famon.frontend.client.dto.SecurityDto;
import za.org.foobar.famon.frontend.client.dto.UserDto;
import za.org.foobar.famon.frontend.client.util.ClientUtil;

/**
 *
 */
public class LoginPortlet extends SmartPortlet {

    private String url;
    private HTML link;
    private HTML username;
    private Dialog loginDialog;
    private HTML loginHtml;
    private LayoutPanel layout;
    private boolean isLoggedIn;

    public LoginPortlet() {
        layout = new LayoutPanel(new RowLayout(true, 2));

        link = new HTML("Login", false);
        link.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
                GWT.log("Style: " + layout.getStyleName(), null);
                
                getLoginUrl();
            }
        });
        username = new HTML("username", false);
        username.setVisible(false);

//        username.setWidth("100%");
//        username.setHeight("40%");
//        link.setWidth("100%");
//        link.setHeight("40%");
//        logoutHtml.setWidth("100%");
//        logoutHtml.setHeight("5%");

        layout.add(username);
        layout.add(link);
//        layout.setAlign(VerticalAlignment.CENTER);
//        layout.setAlign(Alignment.RIGHT);

        initWidget(layout);
    }

    private void getLoginUrl() {
        Factory f = new Factory();
        f.url = "/redirect.jsp?" + URL.encode(ClientUtil.getLocation());
        refresh(f);
    }

    private void showLoginWindow() {
        if (!isLoggedIn) {
            if (loginDialog == null) {
                loginDialog = new Dialog(false, true);
                loginHtml = new HTML();
                loginDialog.setWidget(loginHtml);
                loginDialog.setButtonBarVisible(false);
                loginDialog.setMaximizeVisible(false);
                int width = 500;
                int height = 400;
                loginDialog.setText("Login");
                loginDialog.setSize(Integer.toString(width+20), Integer.toString(height+39));
                StringBuffer s = new StringBuffer();
                s.append("<iframe src=\"\" height = \"").append(height).append("\" width = \"").append(width)
                        .append("\" frameborder = \"0\" scrolling = \"no\"").append("></iframe>");
                loginHtml.setHTML(s.toString());
            }
            Element iframe = DOM.getFirstChild(loginHtml.getElement());
            DOM.setElementAttribute(iframe, "src", url);

            GWT.log("b4 Parent = " + loginDialog.getParent(), null);
            GWT.log("b4 IsAttached = " + loginDialog.isAttached(), null);
            loginDialog.center();
            GWT.log("Parent = " + loginDialog.getParent(), null);
            GWT.log("IsAttached = " + loginDialog.isAttached(), null);
        } else {
            StringBuffer s = new StringBuffer();
            s.append("<iframe src=\"").append(url).append("\" style=\"display:none\"></iframe>");
            link.setHTML(s.toString());
            Famon.getInstance().showBusy();
        }
    }

    public void setUrl(String url) {
        if (url != null) {
            url = url.replaceAll("&amp;w=\\d+&amp;", "&amp;");
            url = url.replaceAll("&amp;h=\\d+&amp;", "&amp;");
        }
        this.url = url;
        update();
        if (url != null) {
            showLoginWindow();
        }
    }

    private void update() {
        Famon famon = Famon.getInstance();
        if (famon == null) {
            return;
        }
        FamonPage page = famon.getPage();
        if (page == null) {
            return;
        }
        SecurityDto security = page.security;

        isLoggedIn = security.isLoggedIn;
        if (isLoggedIn) {
            UserDto user = security.user;
            username.setHTML(user.nickname);
            username.setVisible(true);
            if (security.isAdmin) {
                username.setStyleName("isadmin");
            }
            link.setHTML("<a>Logout</a>");
        } else {
            link.setHTML("<a>Login</a>");
            username.setHTML("");
            username.setVisible(false);
        }
    }

    public WidgetFactory createWidgetFactory() {
        return new Factory();
    }

    public static class Factory extends SmartPortletFactory<LoginPortlet> {
        public String url;

        public Factory() {
        }

        public Factory(Portlet p) {
            super(p);
        }

        public void refresh(LoginPortlet w) {
            super.refresh(w);
            w.setUrl(url);
        }

        public DataTransferObject createDto() {
            return null;
        }

        public LoginPortlet createWidget() {
            return new LoginPortlet();
        }
    }
}
